package com.terracloud.server.service.device;

import com.terracloud.server.common.data.device.DeviceAccessControlMode;
import com.terracloud.server.common.data.device.DeviceAccessControlRule;
import com.terracloud.server.common.data.device.DeviceAccessControlRuleType;
import com.terracloud.server.common.data.id.DeviceAccessControlRuleId;
import com.terracloud.server.common.data.id.DeviceId;
import com.terracloud.server.common.data.id.TenantId;
import com.terracloud.server.common.data.page.PageData;
import com.terracloud.server.common.data.page.PageLink;
import com.terracloud.server.common.data.security.DeviceCredentialsFilter;
import com.terracloud.server.common.transport.auth.DeviceAuthResult;
import com.terracloud.server.dao.device.DeviceAccessControlRuleService;
import com.terracloud.server.queue.util.TbCoreComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
@Slf4j
@TbCoreComponent
public class DeviceAccessControlServiceImpl implements DeviceAccessControlService {

    private final DeviceAccessControlRuleService deviceAccessControlRuleService;

    public DeviceAccessControlServiceImpl(DeviceAccessControlRuleService deviceAccessControlRuleService) {
        this.deviceAccessControlRuleService = deviceAccessControlRuleService;
    }

    @Override
    public DeviceAccessControlRule saveDeviceAccessControlRule(TenantId tenantId, DeviceAccessControlRule rule) {
        rule.setTenantId(tenantId);
        return deviceAccessControlRuleService.saveDeviceAccessControlRule(rule);
    }

    @Override
    public DeviceAccessControlRule findDeviceAccessControlRuleById(TenantId tenantId, DeviceAccessControlRuleId ruleId) {
        return deviceAccessControlRuleService.findDeviceAccessControlRuleById(tenantId, ruleId);
    }

    @Override
    public PageData<DeviceAccessControlRule> findAllDeviceAccessControlRules(PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findAllDeviceAccessControlRules(emptyTenantId, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByTextSearch(String textSearch, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByTextSearch(emptyTenantId, textSearch, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByTypeAndTextSearch(String type, String textSearch, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByTypeAndTextSearch(emptyTenantId, type, textSearch, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByModeAndTextSearch(DeviceAccessControlMode mode, String textSearch, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByModeAndTextSearch(emptyTenantId, mode, textSearch, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByTypeAndModeAndTextSearch(String type, DeviceAccessControlMode mode, String textSearch, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByTypeAndModeAndTextSearch(emptyTenantId, type, mode, textSearch, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByType(String type, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByType(emptyTenantId, type, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByMode(DeviceAccessControlMode mode, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByMode(emptyTenantId, mode, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByTypeAndMode(String type, DeviceAccessControlMode mode, PageLink pageLink) {
        // 创建一个空的租户ID来查询所有规则
        TenantId emptyTenantId = TenantId.fromUUID(new UUID(0L, 0L));
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByTypeAndMode(emptyTenantId, type, mode, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRules(TenantId tenantId, PageLink pageLink) {
        return deviceAccessControlRuleService.findDeviceAccessControlRules(tenantId, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByType(TenantId tenantId, String type, PageLink pageLink) {
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByType(tenantId, type, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByMode(TenantId tenantId, DeviceAccessControlMode mode, PageLink pageLink) {
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByMode(tenantId, mode, pageLink);
    }

    @Override
    public PageData<DeviceAccessControlRule> findDeviceAccessControlRulesByTypeAndMode(TenantId tenantId, String type, DeviceAccessControlMode mode, PageLink pageLink) {
        return deviceAccessControlRuleService.findDeviceAccessControlRulesByTypeAndMode(tenantId, type, mode, pageLink);
    }

    @Override
    public void deleteDeviceAccessControlRule(TenantId tenantId, DeviceAccessControlRuleId ruleId) {
        deviceAccessControlRuleService.deleteDeviceAccessControlRule(tenantId, ruleId);
    }

    @Override
    public DeviceAccessControlMode getAccessControlMode(TenantId tenantId) {
        // 不再使用device_access_control_settings表
        return null;
    }

    @Override
    public void setAccessControlMode(TenantId tenantId, DeviceAccessControlMode mode) {
        // 不再使用device_access_control_settings表
    }

    @Override
    public DeviceAuthResult checkAccess(TenantId tenantId, String deviceId, DeviceCredentialsFilter deviceCredentials, String clientAddress) {
        // 1. 检查设备ID规则
        if (deviceId != null) {
            DeviceAccessControlRule deviceRule = deviceAccessControlRuleService.findDeviceAccessControlRuleByValue(tenantId, deviceId);
            if (deviceRule != null && deviceRule.isEnabled() && deviceRule.getType() == DeviceAccessControlRuleType.DEVICE_ID) {
                // 根据规则中定义的模式判断访问控制
                if (deviceRule.getMode() == DeviceAccessControlMode.BLACKLIST) {
                    // 如果是黑名单模式且找到了规则，则拒绝访问
                    return DeviceAuthResult.of("Device ID is in the blacklist");
                } else if (deviceRule.getMode() == DeviceAccessControlMode.WHITELIST) {
                    // 如果是白名单模式且找到了规则，则允许访问
                    return DeviceAuthResult.of((DeviceId) null);
                }
            }
        }

        // 2. 检查IP地址规则 - 使用新的方法查询所有匹配的规则
        if (clientAddress != null) {
            List<DeviceAccessControlRule> ipRules = deviceAccessControlRuleService.findDeviceAccessControlRulesByValueAndType(clientAddress, com.terracloud.server.common.data.device.DeviceAccessControlRuleType.DEVICE_IP);
            log.info("找到 {} 条匹配的IP规则", ipRules.size());
            for (DeviceAccessControlRule ipRule : ipRules) {
                if (ipRule != null && ipRule.isEnabled() && ipRule.getType() == com.terracloud.server.common.data.device.DeviceAccessControlRuleType.DEVICE_IP) {
                    log.info("检查规则: {}", ipRule);
                    // 根据规则中定义的模式判断访问控制
                    if (ipRule.getMode() == DeviceAccessControlMode.BLACKLIST) {
                        // 如果是黑名单模式且找到了规则，则拒绝访问
                        return DeviceAuthResult.of("Client IP is in the blacklist");
                    } else if (ipRule.getMode() == DeviceAccessControlMode.WHITELIST) {
                        // 如果是白名单模式且找到了规则，则允许访问
                        return DeviceAuthResult.of((DeviceId) null);
                    }
                }
            }
        }

        // 3. 默认允许访问（没有匹配的规则时）
        return DeviceAuthResult.of((DeviceId) null);
    }
}